<?php

namespace app\admin\controller\yxerp;

use ba\Tree;
use app\common\controller\Backend;

/**
 * 通用分类管理
 */
class Category extends Backend
{
    /**
     * Category模型对象
     * @var object
     * @phpstan-var \app\admin\model\yxerp\Category
     */
    protected object $model;
     /**
     * @var Tree
     */
    protected Tree $tree;

    /**
     * 远程select初始化传值
     * @var array
     */
    protected array $initValue;


    /**
     * 是否组装Tree
     * @var bool
     */
    protected bool $assembleTree;
    /**
     * 搜索关键词
     * @var string
     */
    protected string $keyword;

    protected array|string $preExcludeFields = ['id', 'create_time', 'update_time'];

    protected string|array $quickSearchField = ['name'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\yxerp\Category();
        $this->tree  = Tree::instance();

        $this->initValue = $this->request->get('initValue/a', []);
        $this->initValue = array_filter($this->initValue);
        $this->keyword   = $this->request->param('quick_search', '');
        $isTree          = $this->request->param('isTree', true);
        $this->assembleTree = $isTree && !$this->initValue;
    }

    public function index(): void
    {
        if ($this->request->param('select')) {
            $this->select();
        }
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $this->success('', [
            'list'   => $this->getMenus($where),
            'remark' => get_route_remark(),
        ]);
    }

        /**
     * 重写select方法
     * @throws Throwable
     */
    public function select(): void
    {
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $data = $this->getMenus($where);

        // 添加顶级项
    if ($this->request->param('addTopOption')) {
        $topLabel = $this->request->param('topLabel', '顶级');
        array_unshift($data, [
            'id' => 0,
            'name' => $topLabel,
            'pid' => 0
        ]);
    }


        if ($this->assembleTree) {
            $data = $this->tree->assembleTree($this->tree->getTreeArray($data, 'name'));
        }
        $this->success('', [
            'options' => $data
        ]);
    }

     /**
     * 获取菜单列表
     * @throws Throwable
     */
    protected function getMenus($where = []): array
    {
        $pk      = $this->model->getPk();
        $initKey = $this->request->get("initKey/s", $pk);

        $ids = $this->auth->getRuleIds();

        // 如果没有 * 则只获取用户拥有的规则
        if (!in_array('*', $ids)) {
            $where[] = ['id', 'in', $ids];
        }

        if ($this->keyword) {
            $keyword = explode(' ', $this->keyword);
            foreach ($keyword as $item) {
                // 确保 $this->quickSearchField 是数组并且有值
                if (is_array($this->quickSearchField) && count($this->quickSearchField) > 0) {
                    foreach ($this->quickSearchField as $field) {
                        $where[] = [$field, 'like', '%' . $item . '%'];
                    }
                }
            }
        }
        
       
        // 读取用户组所有权限规则
        $rules = $this->model
            ->where($where)
            ->order($this->queryOrderBuilder())
            ->select()
            ->toArray();
        // 如果要求树状，此处先组装好 children
        \think\facade\Log::info('正在组装规则树形数据'.json_encode($rules));
        return $this->assembleTree ? $this->tree->assembleChild($rules) : $rules;
    }
    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */

     public function type(): array
     {
        $list = get_sys_config('', 'yxerpCategory'); // 添加分号
        $this->success('', [
            'list'   => $list['yxerpCategory'],
            'remark' => get_route_remark(),
        ]);
     }
}